package store

import (
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/grand"
	v1 "hotgo/api/api/store/v1"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
)

// StoreList 获取门店列表
func (c *ControllerV1) StoreList(ctx context.Context, req *v1.StoreListReq) (res *v1.StoreListRes, err error) {
	list, total, err := service.SysStoreMember().StoreApiGetStoreByPhone(ctx, req.PageReq)
	if err != nil {
		return nil, err
	}
	for _, v := range list {
		r, err := service.SysStoreMember().StoreData(ctx, &sysin.StoreDataInp{
			StoreId: v.StoreId,
		})
		if err != nil {
			return nil, err
		}
		v.StoreData = r
	}
	res = new(v1.StoreListRes)
	res.List = list
	res.PageRes.Pack(req, total)
	return
}

func (c *ControllerV1) StoreView(ctx context.Context, req *v1.StoreViewReq) (res *v1.StoreViewRes, err error) {
	// 权限检查
	{
		user := contexts.GetUser(ctx)
		var storeMember entity.StoreMember
		if err = dao.StoreMember.Ctx(ctx).Where(dao.StoreMember.Columns().MemberId, user.Id).Where(dao.StoreMember.Columns().StoreId, req.Id).Scan(&storeMember); err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidRequest, "您没有权限查看该门店")
		}
	}

	r, err := service.SysStore().View(ctx, &sysin.StoreViewInp{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}
	res = new(v1.StoreViewRes)
	res.StoreViewModel = r
	return
}

func (c *ControllerV1) StoreMemberAU(ctx context.Context, req *v1.StoreMemberAUReq) (res *v1.StoreMemberAURes, err error) {
	tx, err := dao.StoreMember.DB().Begin(ctx)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	res = new(v1.StoreMemberAURes)
	res.StoreMemberAUModel = new(sysin.StoreMemberAUModel)
	// 门店权限检查
	if req.ID == 0 {
		memberId := contexts.GetUserId(ctx)
		var storeMemberUser entity.StoreMember
		if err = dao.StoreMember.Ctx(ctx).Where(dao.StoreMember.Columns().IsAdmin, 1).
			Where(dao.StoreMember.Columns().MemberId, memberId).
			Where(dao.StoreMember.Columns().StoreId, req.StoreId).Scan(&storeMemberUser); err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidRequest, "您没有权限处理该门店成员")
		}

		// 用户是否存在
		roleId, err := service.AdminRole().GetIdByRoleKey(ctx, "store")
		if err != nil {
			return nil, err
		}
		var member entity.AdminMember
		if err = dao.AdminMember.Ctx(ctx).Where(dao.AdminMember.Columns().Mobile, req.Phone).Where(dao.AdminMember.Columns().RoleId, roleId).Scan(&member); err != nil && !errors.Is(err, sql.ErrNoRows) {
			err = gerror.NewCode(gcode.CodeInternalError, "查询用户失败")
			return nil, err
		}
		err = nil
		var userId int64
		userId = member.Id
		var storeMember entity.StoreMember
		if err = dao.StoreMember.Ctx(ctx).Where(dao.StoreMember.Columns().StoreId, req.StoreId).Where(dao.StoreMember.Columns().MemberId, userId).Scan(&storeMember); err != nil && !errors.Is(err, sql.ErrNoRows) {
			err = gerror.NewCode(gcode.CodeInternalError, "查询门店成员失败")
			return nil, err
		}
		err = nil
		if storeMember.Id != 0 {
			err = gerror.NewCode(gcode.CodeInvalidRequest, "该用户已是门店成员")
			return nil, err
		}
		if member.Id == 0 {
			if req.Avatar == "" {
				req.Avatar = "https://imgs.ynz666.com/test/2025/01/08/MzQ3MGEyMWE3NzYwNmM4N2Y2M2VjNGRkZWJhNGNhMzA=.png"
			}
			// 添加用户
			userId, err = dao.AdminMember.Ctx(ctx).Data(entity.AdminMember{
				RealName:   req.RealName,
				Mobile:     req.Phone,
				Avatar:     req.Avatar,
				Sex:        req.Sex,
				RoleId:     roleId,
				DeptId:     114,
				Status:     1,
				InviteCode: grand.S(12),
				Salt:       grand.S(6),
			}).InsertAndGetId()
			if err != nil {
				return nil, err
			}
		}

		if err = service.SysStoreMember().Edit(ctx, &sysin.StoreMemberEditInp{
			StoreMember: entity.StoreMember{
				StoreId:  req.StoreId,
				MemberId: userId,
				IsAdmin:  0,
			},
		}); err != nil {
			return nil, err
		}
		res.StoreMemberAUModel.Id = userId
	} else {
		res.StoreMemberAUModel.Id = req.ID
		var storeMember entity.StoreMember
		if err = dao.StoreMember.Ctx(ctx).Where(dao.StoreMember.Columns().Id, req.ID).Scan(&storeMember); err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidRequest, "门店成员不存在")
		}
		if _, err = dao.AdminMember.Ctx(ctx).Where(dao.AdminMember.Columns().Id, storeMember.MemberId).Data(g.Map{
			dao.AdminMember.Columns().RealName: req.RealName,
			dao.AdminMember.Columns().Mobile:   req.Phone,
			dao.AdminMember.Columns().Avatar:   req.Avatar,
			dao.AdminMember.Columns().Sex:      req.Sex,
		}).Update(); err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidRequest, "修改用户信息失败")
		}
	}

	return
}

func (c *ControllerV1) StoreMemberList(ctx context.Context, req *v1.StoreMemberListReq) (res *v1.StoreMemberListRes, err error) {
	list, total, err := service.SysStoreMember().List(ctx, &sysin.StoreMemberListInp{
		StoreID: req.StoreID,
	})
	if err != nil {
		return nil, err
	}
	res = new(v1.StoreMemberListRes)
	res.List = list
	res.PageRes.Pack(req, total)
	return
}

func (c *ControllerV1) StoreMemberDelete(ctx context.Context, req *v1.StoreMemberDeleteReq) (res *v1.StoreMemberDeleteRes, err error) {
	if err = service.SysStoreMember().Delete(ctx, &sysin.StoreMemberDeleteInp{
		Id: req.Id,
	}); err != nil {
		return nil, err
	}
	res = new(v1.StoreMemberDeleteRes)
	return res, nil
}

func (c *ControllerV1) StoreData(ctx context.Context, req *v1.StoreDataReq) (res *v1.StoreDataRes, err error) {
	r, err := service.SysStoreMember().StoreData(ctx, &req.StoreDataInp)
	if err != nil {
		return nil, err
	}
	res = new(v1.StoreDataRes)
	res.StoreDataModel = r
	return
}
